package com.nerve.cloudoffice.service.impl;

import java.util.List;

import com.nerve.cloudoffice.common.SessionUtil;
import com.nerve.cloudoffice.domain.Customer;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.domain.dao.CustomerDao;
import com.nerve.cloudoffice.domain.dao.UserDao;
import com.nerve.cloudoffice.service.CustomerService;
import com.nerve.cloudoffice.web.model.CustomerModel;

public class CustomerServiceImpl implements CustomerService{

	private CustomerDao dao;
	private UserDao userDao;
	
	private UserDao getUserDao(){
		if(userDao == null)
			userDao = new UserDao();
		
		return userDao;
	}
	
	private CustomerDao getDao(){
		if(dao == null)
			dao = new CustomerDao();
		
		return dao;
	}
	
	public void add(CustomerModel model) throws Exception {
		Customer customer = model.getCustomer();
		if(customer == null)
			throw new Exception("客户不能为空");
		
		customer.setUser(SessionUtil.getLoginUser());
		
		getDao().save(customer);
	}

	public void list(CustomerModel model) throws Exception {
		String hql = "FROM Customer as c where 1=1";
		
		if(model.getId() > 0){
			hql += " and c.user.id = " + model.getId();
		}
		else{
			User u = SessionUtil.getLoginUser();
			if(u != null){
				hql += " and c.user.id = " + u.getId();
			}
		}
		
		hql += " order by c.id desc";
		List<Customer> list = getDao().getList(hql, 1, 50);
		model.setCustomerList(list);
	}

	public void update(CustomerModel model) throws Exception {
		Customer customer = model.getCustomer();
		if(customer.getId() == 0){
			throw new Exception("更新单子出错：没有id");
		}
		
		Customer cc = getDao().getById(customer.getId());
		customer.setUser(cc.getUser());
		
		System.out.println(customer.getPrice() + " , foundation=" + customer.getFoundation());
		
		getDao().merge(customer);
	}
}